package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author:ahang
 * @create:2022-07-26 20:13
 * @Description:
 */
@Controller
@RequestMapping("/houseImage")
public class HouseImageController extends BaseController {

    @Reference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId, @PathVariable int type, Model model){
        model.addAttribute("houseId",houseId);
        model.addAttribute("type",type);

        return "house/upload";
    }


    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId,
                                 @PathVariable int type,
                                 @RequestParam("file") MultipartFile[] files) throws IOException {
        if(files!= null && files.length>0){
            for (MultipartFile file : files) {
                //上传图片到七牛云
                String originalFilename = file.getOriginalFilename();//获取原始的名称
                String extName = originalFilename.substring(originalFilename.lastIndexOf("."));//获取后缀名
                String fileName = UUID.randomUUID().toString() + extName;
                QiniuUtil.upload2Qiniu(file.getBytes(),fileName);
                //添加图到数据库(不是修改)
                HouseImage houseImage = new HouseImage();
                houseImage.setImageName(fileName);//上传的图片名称根据具体的业务来决定,都可以
                houseImage.setImageUrl("http://rflvieilt.hb-bkt.clouddn.com/"+fileName);
                houseImage.setHouseId(houseId);
                houseImage.setType(type);

                houseImageService.insert(houseImage);
            }
        }
        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{id}") //失败
    public String delete(@PathVariable Long houseId,@PathVariable Long id){
        //删除七牛云上的图片（通过图片id找到图片name）
        HouseImage houseImage = houseImageService.getById(id);
        String imageUrl = houseImage.getImageUrl();
        String newImageUrl = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        QiniuUtil.deleteFileFromQiniu(newImageUrl);//要写文件名,不是外链地址

        //删除数据库中的图片(id_deleted=1)
        houseImageService.delete(id);

        return "redirect:/house/detail/"+houseId;
    }
}
